package com.ssttevee.taskmanagerapp.services;

import java.io.IOException;
import java.util.ArrayList;

import com.ssttevee.taskmanagerapp.R;
import com.ssttevee.taskmanagerapp.TaskManagerApplication;
import com.ssttevee.taskmanagerapp.ViewServersActivity;
import com.ssttevee.taskmanagerapp.tasks.ServerQuery;
import com.ssttevee.taskmanagerapp.tasks.Task;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Build;
import android.os.IBinder;
import android.util.Log;

public class PeriodicPoll extends Service {

	private ArrayList<Task> tasks;
	private ArrayList<String[]> changedServers;
	private TaskManagerApplication app;
	private int sleepInterval = 120 * 1000;
	
	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}
	
	@Override
	public void onCreate() {
		super.onCreate();
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
	}
	
	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		super.onStartCommand(intent, flags, startId);
		Log.d("PeriodicPoll", "Service Started");
		changedServers = new ArrayList<String[]>();
		new Thread(new Runnable(){
			public void run() {
				while(true) {
					app = (TaskManagerApplication) getApplication();
					tasks = app.getCurrentTasks();
					if(isInternetAvailable()) {
						for(Task t : tasks) {
							ServerQuery sq = new ServerQuery();
							if(t.getGs4Port() > 0) {
								try {
									sq.queryServer(t);
									sq.pollServer(t);
								} catch (IOException e) {
								}
							} else {
								try {
									sq.pollServer(t);
								} catch (IOException e) {
								}
							}
	
							t.setMotd(sq.getMotd());
							t.setMaxPlayers(sq.getMaxPlayers());
							t.setOnlinePlayers(sq.getPlayerCount());
							t.setPlayers(sq.getPlayers());
							t.setLatency(sq.getLatency());
							t.setVersion(sq.getVersion());
							t.setTimesOnline(t.getTimesOnline() + (sq.isOnline() ? 1 : 0));
							t.setTimesChecked(t.getTimesChecked() + 1);
							
							if(sq.isOnline() != t.isOnline()) {
								changedServers.add(new String[]{(sq.isOnline() ? "0" : "1"), t.getName()});
							}
							
							t.setOnline(sq.isOnline());
							
							app.saveTask(t);
						}
						
						notifyStatusChange(changedServers);
					}
					
					try {
						Thread.sleep(sleepInterval) ;
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			}
		}).start();
		return START_STICKY;
	}
	
	public void notifyStatusChange(ArrayList<String[]> servers) {
		if(servers.size() > 0) {
			String ns = PeriodicPoll.NOTIFICATION_SERVICE;
			String list[] = new String[]{"", ""};
			NotificationManager mNotificationManager = (NotificationManager) getSystemService(ns);
	
			int icon = R.drawable.status_bar_icon_9;
			if(Build.VERSION.SDK_INT <= 8 ) {
				icon = R.drawable.status_bar_icon;
			} else if(Build.VERSION.SDK_INT >= 11 ) {
				icon = R.drawable.status_bar_icon_11;
			}
			
			for(String[] s : servers) {
				if(s[0] == "0") {
					if(list[0] != "") {
						list[0] = list[0] + ", ";
					}
					list[0] = list[0] + s[1];
				} else if(s[0] == "1") {
					if(list[1] != "") {
						list[1] = list[1] + ", ";
					}
					list[1] = list[1] + s[1];
				}
			}
			
			CharSequence tickerText = "";
			if(list[0].length() <= 0) {
				tickerText = tickerText + list[0] + " has come online";
			} 
			if(list[1].length() <= 0) {
				if(tickerText != "") {
					tickerText = tickerText + ", ";
				}
				tickerText = tickerText + list[1] + " has gone offline";
			}
			
			tickerText = tickerText + "!";
			
			long when = System.currentTimeMillis();
	
			Notification notification = new Notification(icon, tickerText, when);
			notification.flags |= Notification.FLAG_ONLY_ALERT_ONCE | Notification.FLAG_AUTO_CANCEL;
			
			Context context = getApplicationContext();
			CharSequence contentTitle = "McLister";
			CharSequence contentText = tickerText;
			Intent intent = new Intent(this, ViewServersActivity.class);
	
			intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			PendingIntent contentIntent = PendingIntent.getActivity(this, 0, intent, 0);
			notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);
			mNotificationManager.notify(Integer.parseInt("254311485"), notification);
		}
	}
	
	public boolean isInternetAvailable() {
		ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
		return activeNetworkInfo != null;
	}

}
